package com.zhugang.week13.hash;

import java.util.LinkedList;

/**
 * @program algorithms
 * @description: MyHashTable
 * @author: chanzhugang
 * @create: 2022/11/30 23:45
 */
public class MyHashTable {

    private int n = 1000;
    private LinkedList<Student> slots[] = new LinkedList[n];

    public MyHashTable() {
        for (int i = 0; i < n; i++) {
            // 构建每个桶的链表
            slots[i] = new LinkedList<>();
        }
    }

    /**
     * 添加
     *
     * @param id
     * @param student
     */
    public void put(String id, Student student) {
        int hashVal = hashFunction(id);
        LinkedList<Student> linkedList = slots[hashVal];
        linkedList.addFirst(student);
    }

    /**
     * 获取
     *
     * @param id
     * @return
     */
    public Student get(String id) {
        int hashVal = hashFunction(id);
        LinkedList<Student> linkedList = slots[hashVal];
        for (Student student : linkedList) {
            if (student.id.equals(id)) {
                return student;
            }
        }
        return null;
    }

    /**
     * 哈希函数
     *
     * @param id
     * @return
     */
    private int hashFunction(String id) {
        Integer idNum = Integer.valueOf(id);
        return idNum % n;
    }

    public class Student {
        String id;
    }
}